package com.sh.data.engine.domain.shims.sql.select;

import com.sh.data.engine.domain.shims.sql.Context;
import com.sh.data.engine.domain.shims.sql.IllegalQueryException;
import org.apache.commons.lang3.StringUtils;

import java.util.LinkedList;
import java.util.List;

public class Select {

    private Context context;

    private final List<String> columns;

    public Select(Context context) {
        this.context = context;
        this.context.appendWithSeparator("SELECT");
        columns = new LinkedList<>();
    }

    public From from() {
        this.context.appendWithSeparator(StringUtils.join(columns, ","));
        return new From(context);
    }

    public Select all() {
        append("*");
        return this;
    }

    public Select column(String column) {
        append(column);
        return this;
    }

    public Select as(String as) {
        int index = this.columns.size() - 1;
        return as(as, index);
    }

    public Select as(String as, int columnIndex) {
        if (this.columns == null || this.columns.size() == 0) {
            throw new IllegalQueryException("请先添加column");
        }
        String column;
        try {
            column = this.columns.get(columnIndex);
        } catch (IndexOutOfBoundsException exception) {
            throw new IllegalQueryException(String.format("[%s]位置的column不存在", columnIndex));
        }

        this.columns.set(columnIndex, column + " as " + as);

        return this;
    }

    public Select columns(String... columns) {
        if (columns.length == 0) {
            append("*");
        } else {
            for (String column : columns) {
                append(column);
            }
        }

        return this;
    }

    public Select count(String column) {
        append("COUNT(" + column + ")");
        return this;
    }

    private void append(String expression) {
        columns.add(expression);
    }

    @Override
    public String toString() {
        return context.toString();
    }
}
